//
//  News.m
//  MHO
//
//  Created by papo on 2/17/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "News.h"
#import "Lib.h"
#import "Contants.h"
#import "ServiceLib.h"
#import "SBJson.h"
#import "NSString+HTML.h"

@implementation News

+ (News*)newsFromDictionary:(NSDictionary *)dict {
    return [[self alloc] initWithDictionary:dict];
}

+ (News*)getDetailNews:(NSString *)newId {
    NSString* retV = [ServiceLib sendGetRequest:[NSString stringWithFormat:@"http://api.mho.vn/services/News/?newsid=%@", newId]];
    if (retV) {
        SBJsonParser* parser = [[SBJsonParser alloc] init];
        id dict = [parser objectWithString:retV];
        if (dict && [dict isKindOfClass:[NSDictionary class]]) {
            return [News newsFromDictionary:dict];
        }
        
    }
    return nil;
}


+ (NSArray*)newsArrayFromUrl:(NSString *)url {
    NSMutableArray* array = [[NSMutableArray alloc] init];
    
    NSString* retV = [ServiceLib sendGetRequest:url];
    if (retV) {
        SBJsonParser* parser = [[SBJsonParser alloc] init];
        id dict = [parser objectWithString:retV];
        if (dict && [dict isKindOfClass:[NSDictionary class]]) {
            id data = [dict objectForKey:@"DataList"];
            if (data && [data isKindOfClass:[NSArray class]]) {
                [News setArray:array from:data];
            }
        }
        else if (dict && [dict isKindOfClass:[NSArray class]]) {
            [self setArray:array from:dict];
        }
        NSLog(@"url: %@ count: %d", url, array.count);
    }
    
    return array;
}

+ (NSArray*)getHotNews{
    
    return [self newsArrayFromUrl:[Contants urlForKey:kServiceNewsHot]];
}

+ (void)setArray:(NSMutableArray*)array from:(NSArray*)data {
    for (id newsDict in data) {
        if (newsDict && [newsDict isKindOfClass:[NSDictionary class]]) {
            News* app = [News newsFromDictionary:newsDict];
            if (app) {
                [array addObject:app];
            }
        }
    }
}

- (id)initWithDictionary:(NSDictionary *)dict {
    if (self = [super init]) {
        self.newsId = [[dict objectForKey:kNewsModelId] intValue];
        self.title = strCheckNull([dict objectForKey:kNewsModelTitle]);
        self.lead = strCheckNull([dict objectForKey:kNewsModelLead]);
        self.content = strCheckNull([dict objectForKey:kNewsModelContent]);
        self.imagePath = strCheckNull([dict objectForKey:kNewsModeImagePath]);
        self.smallImagePath = strCheckNull([dict objectForKey:kNewsModelSmallImagePath]);
        self.publishDate = strCheckNull([dict objectForKey:kNewsModelPublishDate]);
        self.urlDetail = strCheckNull([dict objectForKey:kNewsModelUrlDetail]);
    }
    return self;
}
@end
